<template>
  <div class="login-container">
    <!-- 打开模态框按钮-->
    <p>照片:</p>
    <div>
      <img v-show="imgSrc" :ref="face" :src="imgSrc" style="width: 300px;height: 300px;" alt="11111"/>
    </div>
    <el-form>
      <el-form-item>
        <el-col :span="1.5">
          <el-button @click="onTake" icon="el-icon-camera" size="small">拍照上传</el-button>
          <el-button size="small" @click="ok">确定上传</el-button>
        </el-col>
      </el-form-item>
    </el-form>

    <!--拍照模态框-->
    <el-dialog title="拍照上传" :visible.sync="visible" @close="onCancel" width="1065px">
      <div class="box">
        <video id="videoCamera" class="canvas" :width="videoWidth" :height="videoHeight" autoplay></video>
        <canvas id="canvasCamera" class="canvas" :width="videoWidth" :height="videoHeight"></canvas>
      </div>
      <div slot="footer">
        <el-button @click="drawImage" icon="el-icon-camera" size="small">拍照</el-button>
        <!-- <el-button @click="getImg" icon="el-icon-camera" size="small">啥？没有摄像头，那从文件中选择上传的照片吧！！！</el-button> -->
        <el-button v-if="os" @click="getCompetence" icon="el-icon-video-camera" size="small">打开摄像头</el-button>
        <el-button v-else @click="stopNavigator" icon="el-icon-switch-button" size="small">关闭摄像头</el-button>
        <el-button class="localImg" icon="el-icon-warning-outline" size="small">

          <input class="uploadImg" type="file" @change="upData($event)" ref="InputFile" name="files"/>
        </el-button>
        <el-button @click="resetCanvas" icon="el-icon-refresh" size="small">重置</el-button>
        <el-button @click="onCancel" icon="el-icon-circle-close" size="small">完成</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>

import {uploadAvatar, uploadUserFace} from "@/api/system/user";
import axios from 'axios'
import store from "@/store";

export default {
  components: {},
  name: "resetFace",
  data() {
    return {
      faceId: "",
      visible: false, //弹窗
      loading: false, //上传按钮加载
      os: false, //控制摄像头开关
      thisVideo: null,
      thisContext: null,
      thisCancas: null,
      videoWidth: 500,
      videoHeight: 400,
      postOptions: [],
      CertCtl: "",
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 总条数
      total: 0,
      // 项目人员表格数据
      akworkerList: [],
      //工种类别数据字典
      workerTypeOptions: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10
      },
      imgSrc: undefined,
      // face:
      // 表单参数
      form: {},
      // 表单校验
      rules: {},
      files: {},
      fileName: "",
      fileList: []

    }

  },
  methods: {
    /*调用摄像头拍照开始*/
    onTake() {
      this.visible = true;
      this.getCompetence();
    },
    onCancel() {
      this.visible = false;
      /* this.resetCanvas();*/
      this.stopNavigator();
    },
    // 调用摄像头权限
    getCompetence() {
      //必须在model中render后才可获取到dom节点,直接获取无法获取到model中的dom节点
      this.$nextTick(() => {
        const _this = this;
        this.os = false; //切换成关闭摄像头
        this.thisCancas = document.getElementById("canvasCamera");
        this.thisContext = this.thisCancas.getContext("2d");
        this.thisVideo = document.getElementById("videoCamera");
        // 旧版本浏览器可能根本不支持mediaDevices，我们首先设置一个空对象
        if (navigator.mediaDevices === undefined) {
          navigator.mediaDevices = {};
        }
        // 一些浏览器实现了部分mediaDevices，我们不能只分配一个对象
        // 使用getUserMedia，因为它会覆盖现有的属性。
        // 这里，如果缺少getUserMedia属性，就添加它。
        if (navigator.mediaDevices.getUserMedia === undefined) {
          navigator.mediaDevices.getUserMedia = function (constraints) {
            // 首先获取现存的getUserMedia(如果存在)
            let getUserMedia =
              navigator.webkitGetUserMedia ||
              navigator.mozGetUserMedia ||
              navigator.getUserMedia;
            // 有些浏览器不支持，会返回错误信息
            // 保持接口一致
            if (!getUserMedia) {
              return Promise.reject(
                new Error("getUserMedia is not implemented in this browser")
              );
            }
            // 否则，使用Promise将调用包装到旧的navigator.getUserMedia
            return new Promise(function (resolve, reject) {
              getUserMedia.call(navigator, constraints, resolve, reject);
            });
          };
        }
        const constraints = {
          audio: false,
          video: {
            width: _this.videoWidth,
            height: _this.videoHeight,
            transform: "scaleX(-1)"
          }
        };
        navigator.mediaDevices
          .getUserMedia(constraints)
          .then(function (stream) {
            // 旧的浏览器可能没有srcObject
            if ("srcObject" in _this.thisVideo) {
              _this.thisVideo.srcObject = stream;
            } else {
              // 避免在新的浏览器中使用它，因为它正在被弃用。
              _this.thisVideo.src = window.URL.createObjectURL(stream);
            }
            _this.thisVideo.onloadedmetadata = function (e) {
              _this.thisVideo.play();
            };
          })
          .catch(err => {
            this.$notify({
              title: "警告",
              message: "没有开启摄像头权限或浏览器版本不兼容.",
              type: "warning"
            });
          });
      });
    },
    //绘制图片
    drawImage() {
      // 点击，canvas画图
      this.thisContext.drawImage(
        this.thisVideo,
        0,
        0,
        this.videoWidth,
        this.videoHeight
      );
      // 获取图片base64链接
      this.imgSrc = this.thisCancas.toDataURL();
      /*const imgSrc=this.imgSrc;*/
    },
    //清空画布
    clearCanvas(id) {
      let c = document.getElementById(id);
      let cxt = c.getContext("2d");
      cxt.clearRect(0, 0, c.width, c.height);
    },
    //重置画布
    resetCanvas() {
      this.imgSrc = "";
      this.clearCanvas("canvasCamera");
    },
    //关闭摄像头
    stopNavigator() {
      if (this.thisVideo && this.thisVideo !== null) {
        this.thisVideo.srcObject.getTracks()[0].stop();
        this.os = true; //切换成打开摄像头
      }
    },
    // 上传预处理
    beforeUpload(file) {
      if (file.type.indexOf("image/") == -1) {
        this.$modal.msgError("文件格式错误，请上传图片类型,如：JPG，PNG后缀的文件。");
      } else {
        const reader = new FileReader();
        reader.readAsDataURL(file);
        reader.onload = () => {
          this.options.img = reader.result;
        };
      }
    },
    ok() {
      if (this.imgSrc != undefined) {
        this.fileName = this.imgSrc;
        const fileName = this.fileName.substring(this.fileName.indexOf(",") + 1)
        let data = {
          file: fileName
        };
        //这里是图片的格式为base64的，所以需要把前面的 data:image/png;base64,去掉，前端可以截取掉，后台也可以，商量一下
        // const fileName=this.fileName.substring(this.fileName.indexOf(",")+1)
        uploadUserFace(data).then(res => {
          //我这里返回的状态成功是00，这里是需要看你们后台返回什么
          if (res.status.state == "00") {
            this.$router.push({name: "起始页面"});
            this.$message({
              message: "操作成功",
              type: "success",
              duration: 1500,
              onClose: () => {
                this.visible = false;
                this.$emit("refreshDataList");
              }
            });
          } else {
            this.$message.error(res.status.errorMessage);
          }
        })
      } else {
        this.$message.error("请先拍照上传");
      }
    },


    //因为有的电脑是没有摄像头的，所以我们需要从本地选取图片进行上传
    upData(event) {
      var reader = new FileReader();
      let fileData = this.$refs.InputFile.files[0];
      reader.readAsDataURL(fileData);
      let _this = this;
      reader.onload = function (e) {
        //这里的数据可以使本地图片显示到页面
        _this.imgSrc = e.srcElement.result;
      };
      // 使用formapi打包
      let formData = new FormData();
      formData.append("fileImg", fileData);
    },
    dataURItoBlob(base64Data) {
      var byteString
      if (base64Data.split(',')[0].indexOf('base64') >= 0)
        byteString = atob(base64Data.split(',')[1])
      else byteString = unescape(base64Data.split(',')[1])
      var mimeString = base64Data
        .split(',')[0]
        .split(':')[1]
        .split(';')[0]
      var ia = new Uint8Array(byteString.length)
      for (var i = 0; i < byteString.length; i++) {
        ia[i] = byteString.charCodeAt(i)
      }
      return new Blob([ia], {type: mimeString})
    }
  },
}
</script>

<!--<style>-->
<!--/* 镜像问题 */-->
<!--video {-->
<!--  transform: rotateY(180deg);-->
<!--  -webkit-transform: rotateY(180deg); /* Safari 和 Chrome */-->
<!--  -moz-transform: rotateY(180deg);-->
<!--}-->
<!--.localImg{-->
<!--  width: 300px;-->
<!--  cursor: pointer;-->
<!--  position: relative;-->
<!--}-->
<!--.uploadImg {-->
<!--  position: absolute;-->
<!--  right: 0;-->
<!--  top: 0;-->
<!--  width: 100%;-->
<!--  height: 100%;-->
<!--  opacity: 0;-->
<!--  cursor: pointer;-->
<!--}-->

<!--</style>-->
